﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SmartSpace.Packaging;
using SmartSpace.Core;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.core
{
    public partial class module_upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            string outDir = Server.MapPath("~/_temp/") + Guid.NewGuid().ToString("D");
            Stream stream = new MemoryStream(_ctlFileModule.FileBytes);
            PackageUtil.DecompressFile(stream, outDir);

            DirectoryInfo di = new DirectoryInfo(outDir);
            string file = di.GetFiles("*.xmml")[0].FullName;
            XModule xModule = PackageUtil.ParseXMML(file);

            // 移动文件
            foreach (XFile xFile in xModule.Files)
            {
                string destFile = Server.MapPath("~\\") + xFile.Path;
                string sourceFile = Path.Combine(outDir, xFile.Publish);

                FileInfo fi = new FileInfo(destFile);
                if (!fi.Directory.Exists)
                {
                    Directory.CreateDirectory(fi.Directory.FullName);
                }

                if (File.Exists(destFile))
                {
                    File.Delete(destFile);
                }
                File.Move(sourceFile, destFile);
            }

            Directory.Delete(outDir, true);

            ICoreService coreService = ServiceLocator.Get<ICoreService>();
            if (coreService.SaveModule(ConvertModule(xModule)))
            {
                Response.Redirect(_ctlLinkBack.NavigateUrl);
            }
        }

        Module ConvertModule(XModule xModule)
        {
            Module module = new Module();
            module.Id = xModule.Id;
            module.Name = xModule.Name;
            module.Caption = xModule.Caption;
            module.Package = xModule.Package;
            module.Settings = xModule.Settings;
            module.Type = xModule.Type;
            module.Version = xModule.Version;
            module.Views = new List<ModuleView>();
            foreach (var xView in xModule.Views)
            {
                ModuleView view = new ModuleView();
                view.Id = xView.Id;
                view.Caption = xView.Caption;
                view.Name = xView.Name;
                view.ModuleId = module.Id;
                module.Views.Add(view);
            }
            return module;
        }
    }
}